package com.you.common.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;

import com.alibaba.citrus.service.resource.ResourceLoadingService;
import com.alibaba.citrus.service.resource.ResourceNotFoundException;

public class FileHelper {

    private ResourceLoadingService resourceLoadingService;
    private File                   uploadPath;

    public static FileHelper getInstance(ResourceLoadingService resourceLoadingService, File uploadPath) {
        FileHelper fileUtil = new FileHelper();
        fileUtil.resourceLoadingService = resourceLoadingService;
        fileUtil.uploadPath = uploadPath;
        return fileUtil;
    }

    /**
     * test.jpg ------------> 01/02/2011-01-11.jpg
     */
    public File getOutputFile(String fileName) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String[] date = simpleDateFormat.format(new Date()).split("-");
        File file = uploadPath;
        for (int i = 0; i < date.length; ++i) {
            file = new File(file, date[i]);
            if (!file.exists()) {
                file.mkdir();
            }
        }
        return new File(file, UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileName));
    }

    /**
     * url -------------> inputStream
     * 
     * @param url
     * @return
     */
    public InputStream getInputStream(String url) {
        try {
            return resourceLoadingService.getResourceAsStream(url);

        } catch (ResourceNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * file -------------> OutputStream
     * 
     * @param url
     * @return
     */
    public OutputStream getOutputStream(File outputFile) {
        try {
            return new FileOutputStream(outputFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * file -------------> url
     * 
     * @param outputFile
     * @return
     */
    public String getUrl(File outputFile) {
        String uploadName = uploadPath.getName();
        String url = outputFile.getPath();
        return url.substring(url.indexOf(uploadName));
    }
}
